<template>
  <div class="charts">
    <div class="charts_top">
      <span class="charts_title">图表布局</span>
      <a-button type="primary" class="button_style" @click="add_charts" icon="plus">
        新建
      </a-button>
    </div>

    <!-- 抽屉 -->
    <a-drawer
      :title="title"
      placement="right"
      :maskClosable="false"
      :visible="drawer"
      width="55%"
      @close="onClose"
      class="echarts_drawer"
    >
      <div class="drawer_content">
        <ConfigCharts :drawer="drawer" ref="config_charts" @current="onCurrentChange" :form="form" >
        </ConfigCharts>
      </div>
      <div class="drawer_divider">
        <a-divider />
        <div class="steps-action">
          <a-button style="margin-right: 8px;" @click="onClose">取消</a-button>
          <a-button style="margin-right: 8px;" v-if="current>0" @click="up_step">上一步</a-button>
          <a-button type="primary" style="margin-right: 8px;" @click="next_step" v-if="current>=0 && current<3 ">下一步</a-button>
          <a-button type="primary" v-if="current==3" @click="onFinish" :loading="loadButton">完成</a-button>
        </div>
      </div>
    </a-drawer>

    <div class="charts_content" :style="[{height:content_height + 'px'}]">
      <div class="charts_check" ref="charts_check">
        <a-row :gutter="14" class="charts_check_row" v-for="item in HeightHang" :key="item">
          <a-col class="gutter-row" :span="1" v-for="item in 24" :key="item" >
            <div class="gutter-box" :style="[{ height: rowHeight+'px' }]" ref="charts_check_row">
            </div>
          </a-col>
        </a-row>
      </div>
      <!--  -->
      <grid-layout
        :layout.sync="layout"
        :col-num="24"
        :row-height="rowHeight"
        :is-draggable="isDrag"
        :is-resizable="isResizable"
        :is-mirrored="false"
        :vertical-compact="false"
        :prevent-collision="true"
        :margin="margin"
        :use-css-transforms="true"
      >
        <grid-item
          v-for="item in layout"
          :x="item.x"
          :y="item.y"
          :w="item.w"
          :h="item.h"
          :i="item.i"
          :key="item.i"
          style="touch-action: none;"
          @moved="movedEvent"
          @resized="resizedEvent"
        >
          <a-card style="width: 100%;height: 100%;padding: 8px 4px 2px 4px;">
            <div class="card-title">
              <div class="card-title_title">
                <div class="chart_title">
                  {{getChartInfo(item.i).title}}
                </div>
                <div class="chart_action">
                  <a-button type="link" size="small" @click="onEditChart(item.i)">编辑</a-button>
                  <a-button type="link" size="small" @click="onDeleteChart(item.i)">删除</a-button>
                </div>
              </div>
              <div class="card-title_remark" v-show="getChartInfo(item.i).remark">
                {{getChartInfo(item.i).remark}}
              </div>
            </div>
            <template v-if="getChartInfo(item.i).type == 'number'">
              <ViewNumber :item="getChartInfo(item.i)" :dataApkdb="dataApkdb" :chartsItem="chartsItem" :rowHeight="rowHeight" :loadingState="loadingState" :ref="'chartconfig'+item.i" />
            </template>
            <template v-else-if="getChartInfo(item.i).type == 'table'">
              <ViewTable :item="getChartInfo(item.i)" :dataApkdb="dataApkdb" :chartsItem="chartsItem" :rowHeight="rowHeight" :loadingState="loadingState" :ref="'chartconfig'+item.i" />
            </template>
            <template v-else-if="getChartInfo(item.i).type == 'retention'">
              <Retention :item="getChartInfo(item.i)" :dataApkdb="dataApkdb" :chartsItem="chartsItem" :rowHeight="rowHeight" :loadingState="loadingState" :ref="'chartconfig'+item.i" />
            </template>
            <template v-else-if="getChartInfo(item.i).type == 'path'">
              <PathView :item="getChartInfo(item.i)" :dataApkdb="dataApkdb" :chartsItem="chartsItem" :rowHeight="rowHeight" :loadingState="loadingState" :ref="'chartconfig'+item.i" />
            </template>
            <template v-else>
              <ChartConfig :item="getChartInfo(item.i)" :dataApkdb="dataApkdb" :chartsItem="chartsItem" :rowHeight="rowHeight" :loadingState="loadingState" :ref="'chartconfig'+item.i" />
            </template>
          </a-card>
        </grid-item>
      </grid-layout>
      <!--  -->
    </div>
  </div>
</template>

<script>
  import VueGridLayout from 'vue-grid-layout';
  import { mapActions, mapMutations, mapState } from 'vuex';
  import ConfigCharts from './components/config_charts.vue';
  import ChartConfig from './components/chart_config/chartsView.vue';
  import ViewNumber from './components/chart_config/view_number.vue';
  import ViewTable from './components/chart_config/view_table.vue';
  import Retention from './components/chart_config/retention.vue';
  import PathView from './components/chart_config/pathView.vue';
  import bus from '@/views/components/bus';
  import _ from "lodash";
  export default {
    data() {
      return {
        isRenderTable: false,
        loadingState: true,
        chartsItem: [],
        layout: [],
        pI: null,
        // 是否可拖拽
        isDrag: true,
        // 行高
        rowHeight: 30,
        // 是否可调整大小
        isResizable: true,
        // 外边距
        margin: [10, 10],
        // 行数
        forTime: 8,
        // 内容宽度
        content_width: null,
        //
        timeout: null,
        content_height: 511,
        title: '新建图表',
        drawer: false,
        loadButton:false,
        current: 0,
        dataApkdb: {},
        form: {
          title: null,
          remark: null,
          type: null,
          dataMapping: null,
          display: {
            series: [
              {
                smooth: false,
                lineStyle: {
                  type: 'solid'
                },
                emphasis: {
                  focus: "self",
                  scale: false
                },
                radius: ['25%', '55%']
              }
            ],
            legend: {
              type: 'scroll',
              orient: 'horizontal',
              top: "0",
              right: "0",
              bottom: "0",
              left: "center",
              show: false
            },
            toolbox: {
              feature: [],
              show: false
            },
            markLine: {
              data: [{}],
              show: false
            },
            label: {
              show: false,
              position: ''
            },
            orderBy: '',
            order: 'asc',
            roam: false,
            visualMap: {
              min: 0,
              max: 100,
              text: ['高', '低'],
              realtime: false,
              calculable: true,
              inRange: {
                  color: ['lightskyblue', 'yellow', 'orangered']
              }
            },
            animated: false,
            unit: ''
          },
          position: {}
        },
        filterForm: [],
        currentIndex: 0
      }
    },
    components: {
      GridLayout: VueGridLayout.GridLayout,
      GridItem: VueGridLayout.GridItem,
      ConfigCharts,
      ChartConfig,
      ViewNumber,
      ViewTable,
      Retention,
      PathView
    },
    watch: {
      drawer (val) {
        if (!val) {
          this.current = 0;
          this.loadButton = false;
          this.form = {
            title: null,
            remark: null,
            type: null,
            dataMapping: null,
            display: {
              series: [
                {
                  smooth: false,
                  lineStyle: {
                    type: 'solid'
                  },
                  emphasis: {
                    focus: "self",
                    scale: false
                  },
                  radius: ['25%', '55%']
                }
              ],
              legend: {
                type: 'scroll',
                orient: 'horizontal',
                top: "0",
                right: "0",
                bottom: "0",
                left: "center",
                show: false
              },
              toolbox: {
                feature: [],
                show: false
              },
              markLine: {
                data: [{}],
                show: false
              },
              label: {
                show: false,
                position: ''
              },
              orderBy: '',
              order: 'asc',
              roam: false,
              visualMap: {
                min: 0,
                max: 100,
                text: ['高', '低'],
                realtime: false,
                calculable: true,
                inRange: {
                    color: ['lightskyblue', 'yellow', 'orangered']
                }
              },
              animated: false,
              unit: ''
            },
            position: {}
          }
        }
      }
    },
    computed: {
      ...mapState('custom', ['report']),
      ...mapState('charts', ['chartList', 'chartsForm']),
      HeightHang () {
        return this.forTime
      },
    },
    methods: {
      ...mapActions('charts', ['set_chart', 'update_chart','get_chartList', 'get_edit_chart', 'delete_chart']),
      ...mapActions('reportManage', ['query_report_detail', 'query_dadaset_data']),
      ...mapMutations('charts', ['SET_MOVE', 'SET_RESIZE']),
      ...mapActions('custom', ['getDsList']),
      getChartInfo (id) {
        let chartVal = null;
        this.chartsItem.forEach(chart=>{
          if (chart.id == id) {
            chartVal = chart;
          }
        })
        return chartVal;
      },
      onClose () {
        this.drawer = false
      },
      // 新建图表
      add_charts () {
        this.title ="新建图表"
        this.drawer = true
        this.currentIndex = null;
      },
      onEditChart (id) {
        this.title ="编辑图表"
        this.drawer = true
        this.get_edit_chart({id, reportId: this.$route.query.id})
          .then(res => {
            this.form = {...res.data}
            let dataMapping = JSON.parse(res.data.dataMapping)
            if(this.form.type == 'table') {
              dataMapping.columns = dataMapping.columns.map(item => {
                return item.datasetId+'-'+item.column + '-' + item.name
              })
            }
            this.form.dataMapping = dataMapping
            this.form.display = JSON.parse(res.data.display)
            this.form.position = JSON.parse(res.data.position)
          })
          .catch(err=>{
            this.$message.error('图表获取失败，原因：'+ err.msg + '！')
          })
      },
      onDeleteChart (id) {
        this.$confirm({
          title: '删除提示',
          content: '删除图表后无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
           this.delete_chart({id, reportId: this.$route.query.id})
            .then(res =>{
              let index = this.chartsItem.findIndex(chart=>{
                return id == chart.id
              });
              this.chartsItem.splice(index, 1);
              let layoutIndex = this.layout.findIndex(out => {
                return id == out.i
              });
              this.layout.splice(layoutIndex, 1);
              this.$message.success('图表删除成功！')
            })
            .catch(err => {
              this.$message.error('图表删除失败，原因：' + err.msg +'！')
            })
          },
          onCancel: () => {},
        })
      },
      // 添加表格
      add_gridLayout () {
        this.forTime += 5
        let arrcs = document.getElementsByClassName("charts_check_row")
        this.content_height = (arrcs[0].offsetHeight+10) * this.forTime
      },
      load_check () {
        window.addEventListener('resize', this.onResize)
      },
      // 计算图表区域内容宽度
      again_computeMedia () {
        this.$nextTick(() => {
          this.rowHeight = this.$refs.charts_check_row[0].offsetWidth
          let check_box = this.$refs.charts_check.offsetHeight
          this.forTime = Math.floor(check_box/(this.rowHeight+10))
          let arr1 = []
          let layout = _.cloneDeep(this.layout);
          arr1 = [...layout].sort((a, b) => b.y - a.y);
          let value = null;
          if (arr1.length > 1) {
            if (arr1[0].h+arr1[0].y >  arr1[1].h+arr1[1].y ) {
              value = arr1[0]
            } else {
              value = arr1[1]
            }
          } else {
            value = arr1[0]
          }
          if (!value) {
            return
          }
          this.forTime = value.y*1 + value.h*1;
          this.content_height = (this.rowHeight + 10) * this.forTime
        })
      },
      /**
       *
       */
      updateChart (newchart) {
        this.update_chart(newchart)
          .then(res=>{
              let index = this.chartsItem.findIndex(chart => {
                  return res.data.id == chart.id
              })
              let newVal = {
                ...res.data,
                position: JSON.parse(res.data.position),
                dataMapping: JSON.parse(res.data.dataMapping),
                display: JSON.parse(res.data.display)
              }
              let layoutIndex = this.layout.findIndex(out => {
                return res.data.id == out.i
              })
              this.chartsItem.splice(index, 1, newVal);
              this.layout.splice(layoutIndex, 1, {...JSON.parse(res.data.position), i: res.data.id})
              this.$nextTick(() => {
                if (res.data.type == 'table') {
                  this.$refs['chartconfig'+res.data.id][0].initTable();
                } else if (res.data.type == 'number') {
                  this.$refs['chartconfig'+res.data.id][0].initNumber();
                } else if (res.data.type == 'path') {
                  this.$refs['chartconfig'+res.data.id][0].reset_sankeyHeight();
                } else if (res.data.type == 'retention') {
                  this.$refs['chartconfig'+res.data.id][0].tableInit();
                } else {
                  this.$refs['chartconfig'+res.data.id][0].initCharts();
                }
              })
              this.again_computeMedia()
          })
          .catch(err => {
            console.error(err);
            this.$message.error('图表更新失败，原因：' + err.msg +'！')
          })
      },
      // 移动
      movedEvent(i, x, y){
        this.changeChart(i);
      },
      // 调整大小
      resizedEvent (i, h, w, Hpx, Wpx) {
        this.changeChart(i);
      },
      /**
       *
       */
      changeChart (i) {
          let charts = _.cloneDeep(this.chartsItem);
          let index = charts.findIndex(chart => {
            return i == chart.id
          })
          let current = this.layout.findIndex(ly => {
            return i == ly.i
          })
          let position = this.layout[current];
          // delete position.i
          let moveCharts = {
                  ...charts[index],
                  display: JSON.stringify(charts[index].display),
                  dataMapping: JSON.stringify(charts[index].dataMapping),
                  position: JSON.stringify(position)
              };
          this.updateChart(moveCharts);
      },
      // 当页面宽度发生变化
      onResize () {
          this.timeout && clearTimeout(this.timeout);
          this.$nextTick(() => {
            this.timeout = setTimeout(() => {
                this.content_width = this.$refs.charts_check.offsetWidth;
                this.again_computeMedia()
            }, 500);
          })
      },
      computePosition () {
        let arr = _.cloneDeep(this.layout);
        if (arr.length) {
            arr.sort((a, b) => {
                return a.y - b.y
            })
            return arr[arr.length-1].y*1 + arr[arr.length-1].h*1
        } else {
            return 0
        }
      },
      // 完成
      onFinish () {
        let currentViewDisplay = {},
            formDisplay = this.form.display,
            cloneForm = _.cloneDeep(this.form);
        // 折线图、面积图
        if (this.form.type == 'line' || this.form.type == 'area') {
          currentViewDisplay = JSON.parse(JSON.stringify(formDisplay))
          currentViewDisplay.series = []
          currentViewDisplay.series[0] = {}
          currentViewDisplay.series[0].lineStyle = formDisplay.series[0].lineStyle
          currentViewDisplay.series[0].smooth = formDisplay.series[0].smooth
          currentViewDisplay.series[0].emphasis = formDisplay.series[0].emphasis
          if (this.form.type == 'area') {
            currentViewDisplay.series[0].areaStyle = {}
          }
        // 柱状图、条形图
        }  else if (this.form.type == 'bar' || this.form.type == 'strip') {
          currentViewDisplay.series = []
          currentViewDisplay.series[0] = {}
          currentViewDisplay.series[0].emphasis = formDisplay.series[0].emphasis
          currentViewDisplay.markLine = formDisplay.markLine
          currentViewDisplay.legend = formDisplay.legend
          currentViewDisplay.toolbox = formDisplay.toolbox
        // 饼图、环图
        } else if (this.form.type == 'pie' || this.form.type == 'loop') {
          currentViewDisplay.series = []
          currentViewDisplay.series[0] = {}
          currentViewDisplay.series[0].radius = formDisplay.series[0].radius
          currentViewDisplay.series[0].smooth = formDisplay.series[0].smooth
          currentViewDisplay.label = formDisplay.label
          currentViewDisplay.series[0].emphasis = formDisplay.series[0].emphasis
          currentViewDisplay.legend = formDisplay.legend
          currentViewDisplay.toolbox = formDisplay.toolbox
        // 表格
        } else if (this.form.type == 'table') {
          currentViewDisplay.orderBy = formDisplay.orderBy
          currentViewDisplay.order = formDisplay.order
          currentViewDisplay.page = formDisplay.page
        // 地图
        } else if (this.form.type == 'map') {
          currentViewDisplay.roam = formDisplay.roam
          currentViewDisplay.label = formDisplay.label
          currentViewDisplay.visualMap = formDisplay.visualMap
          currentViewDisplay.toolbox = formDisplay.toolbox
        // 组合图
        } else if (this.form.type == 'group') {
          currentViewDisplay.series = []
          currentViewDisplay.series[0] = {}
          currentViewDisplay.series[0].emphasis = formDisplay.series[0].emphasis
          currentViewDisplay.markLine = formDisplay.markLine
          currentViewDisplay.legend = formDisplay.legend
          currentViewDisplay.toolbox = formDisplay.toolbox
        // 数字指标块
        } else if (this.form.type == 'number') {
          currentViewDisplay.animated = formDisplay.animated
          currentViewDisplay.unit = formDisplay.unit
        } else if (this.form.type == 'funnel') {
          currentViewDisplay.series = []
          currentViewDisplay.series[0] = {}
          currentViewDisplay.label = formDisplay.label
          currentViewDisplay.series[0].emphasis = formDisplay.series[0].emphasis
          currentViewDisplay.legend = formDisplay.legend
          currentViewDisplay.toolbox = formDisplay.toolbox
        } else if (this.form.type == 'path') {
          currentViewDisplay.highLightPath = formDisplay.highLightPath
          currentViewDisplay.showDetails = formDisplay.showDetails
        }
        this.form.display = currentViewDisplay
        this.form = {
          ...this.form,
          reportId: this.$route.query.id,
          display: JSON.stringify(this.form.display),
        }
        if (this.form.type == 'table') {
          let columns = this.form.dataMapping.columns.map(item => {
            return {datasetId: item.split('-')[0], column: item.split('-')[1], name: item.split('-')[2]}
          })
          this.form.dataMapping = {...this.form.dataMapping, columns}
        }
        this.form.dataMapping = JSON.stringify(this.form.dataMapping)

        if (this.layout.length) {
            if (this.form.id) {
                // delete this.form.position.i
                this.form.position = JSON.stringify(this.form.position)
            } else {
                this.form.position = JSON.stringify({ 'x': 0, 'y': this.computePosition(), 'w': 12, 'h': 8})
            }
        } else {
            this.form.position = JSON.stringify({ 'x': 0, 'y': 0, 'w': 12, 'h': 8 })
        }

        this.loadButton = true
        if (this.form.id) {
          this.update_chart({...this.form})
            .then(res =>{
              this.drawer = false;
              this.$message.success('图表编辑成功！')
              this.$nextTick(() => {
                this.renderCharts({
                  ...res.data,
                  position: JSON.parse(res.data.position),
                  dataMapping: JSON.parse(res.data.dataMapping),
                  display: JSON.parse(res.data.display)
                });
              })
            })
            .catch(err => {
              this.form = cloneForm;
              this.$message.error('图表编辑失败，原因：' + err.msg +'！')
            })
            .finally( _ =>{
              this.loadButton = false;
            })
        }else{
          this.set_chart({...this.form})
            .then(res =>{
              this.drawer = false;
              this.$message.success('图表创建成功！')
              this.renderCharts({
                ...res.data,
                position: JSON.parse(res.data.position),
                dataMapping: JSON.parse(res.data.dataMapping),
                display: JSON.parse(res.data.display)
              });
            })
            .catch(err => {
              this.form = cloneForm;
              this.$message.error('图表创建失败，原因：' + err.msg +'！')
            })
            .finally( _ =>{
              this.loadButton = false;
            })
        }

      },
      // 重新获取数据
      renderCharts (data) {
        let id = data.id;
        let index = this.chartsItem.findIndex(chart =>{
          return id == chart.id
        });
        let layoutIndex = this.layout.findIndex(out => {
          return id == out.i
        })
        if(index != -1 && layoutIndex != -1) {
          this.chartsItem.splice(index, 1, data);
          this.layout.splice(layoutIndex, 1, {...data.position, i: data.id})
        } else {
          this.chartsItem.push(data)
          this.layout.push({...data.position, i: data.id})
        }
        this.$nextTick(() => {
          if (data.type == 'table') {
            this.$refs['chartconfig'+id][0].initColumns();
            this.$refs['chartconfig'+id][0].initTable();
          } else if (data.type == 'number') {
            this.$refs['chartconfig'+id][0].initNumber();
          } else if (data.type == 'path') {
            this.$refs['chartconfig'+id][0].reset_sankeyHeight();
          } else if (data.type == 'retention') {
            this.$refs['chartconfig'+id][0].tableInit();
          } else {
            this.$refs['chartconfig'+id][0].initCharts();
          }
        })
        this.again_computeMedia()
      },
      // 上一步
      up_step () {
        this.$refs.config_charts.up_step()
      },
      // 下一步
      next_step (){
        this.$refs.config_charts.next_step()
      },
      changeMapping (val){
        if (!this.form.id) {
          if (val == 'object') {
            this.form.dataMapping = {}
          } else {
            this.form.dataMapping = []
          }
        }
      },
      // current 赋值
      onCurrentChange (current) {
        this.current = current
      },
      /**
       * 使用一个数组渲染页面
       */
      initData () {
        // 获取报表的charts图表
        this.get_chartList({reportId: this.$route.query.id})
          .then(res => {
            this.chartsItem = res.data.map(item => {
              return {...item, dataMapping: JSON.parse(item.dataMapping), display: JSON.parse(item.display), position: JSON.parse(item.position)}
            })
            this.layout = res.data.map(item => {
              return {...JSON.parse(item.position), i: item.id}
            })
          })
        // 获取对应报表下的所有图标信息
        this.query_report_detail({id: this.$route.query.id})
          .then(detail => {
            // 当前报表使用的数据集
            const datasetIds = detail.data.datasetIds
            //
            const form = {}
            //
            const filters = detail.data.filters.map( filter => {
              // 根据筛选信息的控件类型对数据做处理
              if (filter.type == 'date-range') {
                if (JSON.parse(filter.defaultValue).type == "absolute") {
                  let date_Array = (JSON.parse(filter.defaultValue).values);
                  this.$set(form, filter.name, [this.moment(date_Array[0]).format('YYYY-MM-DD'), this.moment(date_Array[1]).format('YYYY-MM-DD') ]);
                } else {
                  let date_Array = (JSON.parse(filter.defaultValue).values).split(',');
                  this.$set(form, filter.name, [this.moment().subtract(parseInt(date_Array[0]), 'days').format('YYYY-MM-DD'), this.moment().subtract(parseInt(date_Array[1]), 'days').format('YYYY-MM-DD') ]);
                }
              } else {
                // 当控件类型为多选下拉菜单，需要将默认值转为数组
                if (filter.type == 'selects') {
                  form[filter.name] = filter.defaultValue ? filter.defaultValue.split(',') : filter.defaultValue;
                } else {
                  form[filter.name] = filter.defaultValue;
                }
              }
              return  {...filter, config: JSON.parse(filter.config), defaultValue: filter.type == 'date-range' ? JSON.parse(filter.defaultValue) : filter.defaultValue}
            })

            let queryForm = this.queryFilterForm(form, filters, datasetIds);
            let wait = [];
            this.loadingState = true;
            datasetIds.forEach(data => {
              wait.push(this.data_Promise({id: data, filter: JSON.stringify(queryForm[data])}))
            })
            let promiseAll = wait.filter(item => {
              if(item) return item
            })
            Promise.all(promiseAll.map(item=>item.catch(()=>{status: 'failed'})))
            .then(res => {
              let chartconfig = [];
              for (let ref in this.$refs) {
                if (ref.includes('chartconfig')) {
                  chartconfig.push(ref)
                }
              }

              this.$nextTick(() => {
                chartconfig.forEach(chart => {
                  let type = this.$refs[chart][0].item.type,
                      vNode = this.$refs[chart][0];
                  if (type == 'table') {
                    vNode.initTable();
                    vNode.initColumns();
                  } else if (type == 'number') {
                    vNode.initNumber();
                  } else if (type == 'path') {
                    vNode.reset_sankeyHeight();
                  } else if (type == 'retention') {
                    vNode.tableInit();
                  } else {
                    vNode.initCharts();
                  }
                })
                this.loadingState = false;
              })
              this.again_computeMedia()
            })
            .catch(err => {
              this.loadingState = false;
            })
            this.load_check()
            this.$nextTick(() => {
              this.onResize()
            })
          })
          this.getDsList({id: this.$route.query.id});
      },
      queryFilterForm (Query, filters, datasetIds) {
        // 以{key:value}的形式生成每个数据集的查询参数
        let filterValue = {}
        for (let j = 0; j < datasetIds.length; j++) {
          // 生成每个数据集对应的数组存放条件
          filterValue[datasetIds[j]] = []
          for (let i = 0; i < filters.length; i++) {
            // 控件类型为日期时，需要做start和end的特殊处理
            if (filters[i].type == 'date-range') {
              let config_start = filters[i].config.start,
                  config_end = filters[i].config.end,
                  count = 0;
              for (let m = 0; m < config_start.length; m++) {
                if (config_start[m].datasetId == datasetIds[j]) {
                  for (let key in Query) {
                    if (filters[i].name == key) {
                      filterValue[datasetIds[j]].push({
                        filterName: config_start[m].filterName,
                        value: Query[key][count]
                      })
                      count ++;
                    }
                  }
                }
              }
              for (let n = 0; n < config_end.length; n++) {
                if (config_end[n].datasetId == datasetIds[j]) {
                  for (let key in Query) {
                    if (filters[i].name == key) {
                      filterValue[datasetIds[j]].push({
                        filterName: config_end[n].filterName,
                        value: Query[key][count]
                      })
                      count ++;
                    }
                  }
                }
              }
            } else {
              let config_item = filters[i].config
              for (let o = 0; o <config_item.length; o++) {
                if (config_item[o].datasetId == datasetIds[j]) {
                  for(let key in Query) {
                    if (filters[i].name == key) {
                      // 当控件类型为单选和多选 需要转换数据类型
                      if (filters[i].type == 'select' || filters[i].type == 'selects') {
                        if (Query[key]) {
                          filterValue[datasetIds[j]].push({
                            filterName: config_item[o].filterName,
                            value: Query[key] instanceof Array ? Query[key] : Query[key].split(',')
                          })
                        } else {
                          filterValue[datasetIds[j]].push({
                            filterName: config_item[o].filterName,
                            value: Query[key]
                          })
                        }
                      } else {
                        filterValue[datasetIds[j]].push({
                          filterName: config_item[o].filterName,
                          value: Query[key]
                        })
                      }
                    }
                  }
                }
              }
            }
          }
        }
        return filterValue
      },
      data_Promise (val) {
        return new Promise((resolve, reject) => {
          this.query_dadaset_data(val)
            .then(res=>{
              this.$set(this.dataApkdb, val.id, res.data)
              resolve(res.data)
            })
            .catch(err=>{
              reject(err)
              console.error(err)
            })
        })
      }
    },
    mounted() {
      this.rowHeight = this.$refs.charts_check_row[0].offsetWidth
      this.initData()
      bus.$on('onChartChange',(res)=> {
        this.form = {
          ...this.form,
          type: res,
          dataMapping: ['table', 'number', 'funnel', 'path', 'retention'].includes(res) ? {} : [],
          display: {
            series: [
              {
                smooth: false,
                lineStyle: {
                  type: 'solid'
                },
                emphasis: {
                  focus: "self",
                  scale: false
                },
                radius: res == 'pie' ? ['0%', '50%'] : ['33%', '55%']
              }
            ],
            legend: {
              type: 'scroll',
              orient: ['pie', 'loop'].includes(res) ? 'vertical' : 'horizontal',
              top: ['pie', 'loop'].includes(res) ? "center" : '0',
              right: "0",
              bottom: "0",
              left: ['pie', 'loop'].includes(res) ? "0" : 'center',
              show: false
            },
            toolbox: {
              feature: [],
              show: false
            },
            markLine: {
              data: [{}],
              show: false
            },
            label: {
              show: false,
              position: ''
            },
            orderBy: '',
            order: 'asc',
            roam: false,
            visualMap: {
              min: 0,
              max: 100,
              text: ['高', '低'],
              realtime: false,
              calculable: true,
              inRange: {
                  color: ['lightskyblue', 'yellow', 'orangered']
              }
            },
            animated: false,
            unit: ''
          }
        }
      })
    },
  }
</script>

<style scoped>
.charts,
.charts_top {
  width: 100%;
}

.charts {
  height: 100%;
}

.charts_content{
  height: calc(100% - 45px);
  position: relative;
  padding-top: 10px;
}

.charts_top {
  display: inline-block;
}

.charts_top>>>.button_style {
  float: right;
}

.charts_title {
  float: left;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0,0,0,.85);
  line-height: 32px;
}

.vue-grid-item {
  background-color: #ccc;
}

.vue-grid-layout {
  height: 100%;
}

.charts_check{
  position: absolute;
  width: 100%;
  height: 100%;
}

.charts_check >>> .ant-row > div {
  background: transparent;
  border: 0;
}
.gutter-box {
  border: 1px solid #ccc;
  border-radius: 7px;
}

.charts_check_row {
  margin-left: 3px !important;
  margin-right: 3px !important;
  margin-top: 10px;
}

.add_charts {
  position: absolute;
  right: 0;
  bottom: -42PX;
}

/* .echarts_drawer>>>.ant-drawer-wrapper-body {
  display: flex;
  flex-direction: column;
} */

.echarts_drawer>>>.ant-drawer-body {
  height: calc(100% - 55px);
  position: relative;
}

.drawer_content {
  position: absolute;
  bottom: 60px;
  top: 24px;
  right: 24px;
  left: 24px;
}

.echarts_drawer >>> .ant-divider-horizontal {
  margin: 8px 0;
}

.steps-action {
  float: right;
}

.charts_content>>>.ant-card-body {
  position: relative;
  padding: 0 !important;
}

/* .card-title {
  height: 60px;
} */

.card-title_title {
  display: flex;
  justify-content: space-between;
}

.chart_title {
  font-size: 14px;
  color: #555;
  text-indent: 10px;
  line-height: 30px;
}

.card-title_remark {
  padding-right: 20px;
  font-size: 12px;
  line-height: 20px;
  color: #8492a6;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-indent: 10px;
  margin-bottom: 1px;
}

.chart_action {
  display: flex;
  align-items: center;
}

.drawer_divider {
  height: 60px;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

</style>

<style>
.ant-drawer-wrapper-body {
  overflow: hidden !important;
}
</style>
